package com.hunttown.mes.manage.controller._mes;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.qcloud.qcloudcos.CosConstants;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.*;
import com.hunttown.mes.rpc.domain.enums.mes.produce.OrderStatusEnum;
import com.hunttown.mes.rpc.domain.enums.mes.produce.ProduceModeEnum;
import com.hunttown.mes.rpc.domain.enums.pay.ReceiveWayEnum;
import com.hunttown.mes.rpc.domain.enums.purchase.ProductTypeEnum;
import com.hunttown.mes.rpc.domain.enums.task.PriorityTypeEnum;
import com.hunttown.mes.rpc.domain.query.MesOrderMaterialDTOQuery;
import com.hunttown.mes.rpc.domain.query.MesSaleOrderDTOQuery;
import com.hunttown.mes.rpc.domain.query.MesSaleOrderDetailDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2022-03-30 15:35:05
 */
@Controller
@RequestMapping(value = "/mes/order")
public class MesSaleOrderController {

    private final static Logger logger = LoggerFactory.getLogger(MesSaleOrderController.class);

    private final MesSaleOrderManageService mesSaleOrderService;
    private final MesSaleOrderDetailManageService saleOrderDetailService;
    private final MesOrderMaterialManageService orderMaterialService;
    private final MesProductManageService productService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;
    private final TransportPurchaseManageService purchaseService;
    private final TransportPurchaseDetailManageService purchaseDetailService;
    private final TransactionService transactionService;
    private final WorkflowApplyManageService applyManageService;

    @Autowired
    public MesSaleOrderController(MesSaleOrderManageService mesSaleOrderService, MesSaleOrderDetailManageService saleOrderDetailService, MesOrderMaterialManageService orderMaterialService, MesProductManageService productService, AnalysisManageManageService manageService, ModelService modelService, TransportPurchaseManageService purchaseService, TransportPurchaseDetailManageService purchaseDetailService, TransactionService transactionService, WorkflowApplyManageService applyManageService) {
        this.mesSaleOrderService = mesSaleOrderService;
        this.saleOrderDetailService = saleOrderDetailService;
        this.orderMaterialService = orderMaterialService;
        this.productService = productService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.purchaseService = purchaseService;
        this.purchaseDetailService = purchaseDetailService;
        this.transactionService = transactionService;
        this.applyManageService = applyManageService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, MesSaleOrderDTOQuery dtoQuery) {

        //初始化日期（90天）
        if (StringUtils.isBlank(dtoQuery.getDaterange())) {
            dtoQuery.setDaterange(String.format("%s ~ %s", DateConvertUtils.getPastDate(90), DateConvertUtils.getPastDate(0)));
        }

        dtoQuery.setOrderBy("order by id desc");
        Page<MesSaleOrderDTO> dataPage = mesSaleOrderService.getForPage(dtoQuery);

        for (MesSaleOrderDTO item : dataPage.getItems()) {
            item.setCompanyName(modelService.getCompanyName(item.getCompanyId()));
            item.setProduceModeName(ProduceModeEnum.getEnumByKey(item.getProduceMode()));
            item.setStatusName(OrderStatusEnum.getEnumByKey(item.getStatus()));
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        //订单日期
        if (StringUtils.isNotBlank(dtoQuery.getDaterange())) {
            String[] date = dtoQuery.getDaterange().split("~");
            if (date.length == 2) {
                model.addAttribute("startDate", date[0].trim());
                model.addAttribute("endDate", date[1].trim());
            }
        }

        //客户信息
        modelService.getCompayPage(model, 2);

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        String[] menus = {"X-D-KHDD-BJ", "X-D-KHDD-SC", "X-D-KHDD-DDFH"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "mes/order/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, Model model, Integer id) {
        id = (id == null ? 0 : id);

        MesSaleOrderDTO obj;

        if (id > 0) {
            obj = mesSaleOrderService.getById(id);

            //region 收货区域
            if (obj.getReceiveProvince() > 0) {
                modelService.getRegionPage(model, obj.getReceiveProvince(), "cityPage");
            }
            if (obj.getReceiveCity() > 0) {
                modelService.getRegionPage(model, obj.getReceiveCity(), "countyPage");
            }
            //endregion

            //region 获取销售明细列表
            MesSaleOrderDetailDTOQuery detailQuery = new MesSaleOrderDetailDTOQuery();
            detailQuery.setOrderId(id);
            detailQuery.setStopFlag(0);
            detailQuery.setPageSize(100);
            Page<MesSaleOrderDetailDTO> productPage = saleOrderDetailService.getForPage(detailQuery);
            model.addAttribute("productList", productPage.getItems());
            //endregion

            //region 获取客户原料列表
            MesOrderMaterialDTOQuery materiallQuery = new MesOrderMaterialDTOQuery();
            materiallQuery.setTableId(203);
            materiallQuery.setRecordId(id);
            materiallQuery.setPageSize(100);
            Page<MesOrderMaterialDTO> materialPage = orderMaterialService.getForPage(materiallQuery);
            for (MesOrderMaterialDTO item : materialPage.getItems()) {
                item.setGoodsTypeName(ProductTypeEnum.getEnumByKey(item.getGoodsType()));
            }
            model.addAttribute("partsDetailList", materialPage.getItems());
            //endregion

            //region 获取已上传文件
            modelService.getUploadPage(model, obj.getContractDoc());
            model.addAttribute("mainPicId", 0); //主图
            //endregion

        } else {
            obj = new MesSaleOrderDTO();
            obj.setId(0);
            obj.setEmergentLevel(3);
            obj.setPayWay(5);
            obj.setAmount(BigDecimal.ZERO);
            obj.setReceiveDate(new Date());
            obj.setPayDate(new Date());
            obj.setOperateDate(new Date());
            obj.setStatus(0);

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            obj.setOperator(curr_obj.getId());

            obj.setOrderNo(GeneralUtils.GenTimeSeries(4, null, null));
        }
        model.addAttribute("Obj", obj);

        //客户信息
        modelService.getCompayPage(model, 9);

        //经办人
        modelService.getManagerPage(model);

        //紧急程度
        model.addAttribute("emergentLevelList", PriorityTypeEnum.getEnumList());

        //付款方式
        model.addAttribute("payWayList", ReceiveWayEnum.getEnumList());

        //生产方式
        model.addAttribute("produceModeList", ProduceModeEnum.getEnumList());

        //订单状态
        model.addAttribute("orderStatusList", OrderStatusEnum.getEnumList());

        //区域信息
        modelService.getRegionPage(model, 0, "provincePage");

        //region 文件上传使用
        model.addAttribute("uploadTableName", "mes_sale_order");
        model.addAttribute("uploadRecordId", obj.getId());
        model.addAttribute("labelTips", "销售合同");
        model.addAttribute("btnTips", "上传合同");
        model.addAttribute("modalTips", "合同上传");

        String uploadPrefix = CosConstants.getStorageFolder(null);
        model.addAttribute("uploadPrefix", uploadPrefix);
        //endregion

        return "mes/order/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, MesSaleOrderDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        int orderid = 0; //新生成的订单ID
        int order_apply = 0; //新生成的审批ID

        try {
            //日期
            objDTO.setReceiveDate(DateConvertUtils.strToDate(objDTO.getReceiveDateSr()));
            objDTO.setPayDate(DateConvertUtils.strToDate(objDTO.getPayDateSr()));
            objDTO.setOperateDate(DateConvertUtils.strToDate(objDTO.getOperateDateSr()));

            //单选
            if (objDTO.getBdConfirm() == null) {
                objDTO.setBdConfirm(0);
            }
            if (objDTO.getBomConfirm() == null) {
                objDTO.setBomConfirm(0);
            }
            if (objDTO.getTestConfirm() == null) {
                objDTO.setTestConfirm(0);
            }
            if (objDTO.getMarkConfirm() == null) {
                objDTO.setMarkConfirm(0);
            }
            if (objDTO.getTagConfirm() == null) {
                objDTO.setTagConfirm(0);
            }
            if (objDTO.getPackageConfirm() == null) {
                objDTO.setPackageConfirm(0);
            }

            //处理上传ID
            objDTO.setContractDoc(FormatUtils.formatCommas(objDTO.getIsUpload()));

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                MesSaleOrderDTOQuery query = new MesSaleOrderDTOQuery();
                query.setOrderNo(objDTO.getOrderNo());
                MesSaleOrderDTO obj = mesSaleOrderService.getByQuery(query);

                if (obj != null && obj.getId() > 0) {
                    //说明此记录已经存在，不能重复插入
                    map = OperateCode.CompositionResult(map, -10, "此订单已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO.setStockStatus(0);
                objDTO = mesSaleOrderService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                orderid = objDTO.getId(); //赋值

                //region 创建审批单
                Map<String, String> param = new HashMap<>();
                param.put("applyTitle", String.format("%s的（%s）审批", modelService.getManageName(objDTO.getOperator()), objDTO.getOrderTitle().replace("审批", "")));

                //[改版后]审批人走的是会员系统
                param.put("firstExector", modelService.getUserIdByAdminId(objDTO.getOperator()) + "");

                Integer applyId = transactionService.createApplyWithout("sale_order_approve", "mes_sale_order", objDTO.getId(), objDTO.getAdminId(), param);
                if (applyId > 0) {
                    order_apply = applyId;

                    //更新出库表中的applyId
                    MesSaleOrderDTO updateDto = new MesSaleOrderDTO();
                    updateDto.setId(objDTO.getId());
                    updateDto.setApplyId(applyId);
                    mesSaleOrderService.updateInfoById(updateDto);

                } else {
                    //审批流程生成失败 删除已经生成的出库单
                    mesSaleOrderService.delete(objDTO.getId());

                    //程序终止，返回失败信息
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
                //endregion

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = mesSaleOrderService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region [01].销售订单明细表.保存成功后更新
            String[] f_d_id = request.getParameterValues("f_d_id");
            String[] f_productid = request.getParameterValues("f_productid");
            String[] f_price = request.getParameterValues("f_price");
            String[] f_ordercount = request.getParameterValues("f_ordercount");
            String[] f_remark = request.getParameterValues("f_remark");

            //1.获取已保存的销售明细
            MesSaleOrderDetailDTOQuery historyQuery = new MesSaleOrderDetailDTOQuery();
            historyQuery.setOrderId(objDTO.getId());
            historyQuery.setStopFlag(0);
            historyQuery.setPageSize(100);
            Page<MesSaleOrderDetailDTO> historyPage = saleOrderDetailService.getForPage(historyQuery);

            //2. 保存到数据库
            if (f_d_id != null && f_d_id.length > 0) {

                List<Integer> newDetailIds = new ArrayList<>();  //提交上来的，已保存过的ID
                MesProductDTO productObj;  //型号规格
                MesProductDTO pObj;  //它的父产品
                MesSaleOrderDetailDTO insert;

                for (int i = 0; i < f_d_id.length; i++) {
                    int ordercount = Integer.parseInt(f_ordercount[i]);
                    if (ordercount <= 0) {
                        continue;
                    }

                    int productid = Integer.parseInt(f_productid[i]);
                    if (productid <= 0) {
                        continue;
                    }

                    productObj = productService.getById(productid);
                    if (productObj == null) {
                        continue;
                    }

                    pObj = productService.getById(productObj.getParentId());
                    if (pObj == null) {
                        continue;
                    }

                    insert = new MesSaleOrderDetailDTO();
                    insert.setOrderType(0);
                    insert.setOrderId(objDTO.getId());
                    insert.setProductId(productid);
                    insert.setProductName(pObj.getProductName());
                    insert.setProductCode(pObj.getProductCode());
                    insert.setChipName(pObj.getChipName());
                    insert.setSpecialName(productObj.getSpecialName());
                    insert.setUnit(pObj.getUnit());
                    insert.setPackageMode(pObj.getPackageMode());
                    insert.setStoreId(pObj.getStorage());
                    insert.setSalePrice(productObj.getSalePrice());
                    insert.setPrice(new BigDecimal(f_price[i]));
                    insert.setOrderCount(ordercount);
                    insert.setStoreCount(0);
                    insert.setProduceCount(0);
                    insert.setRealProduceCount(0);
                    insert.setProductStatus(productObj.getProductStatus());
                    insert.setRemark(f_remark[i]);
                    insert.setAdminId(curr_obj.getId());
                    insert.setCreateTime(new Date());
                    insert.setStopFlag(0);
                    insert.setDeleteFlag(0);

                    //更新或插入
                    int id = Integer.parseInt(f_d_id[i]);
                    if (id > 0) {
                        //更新
                        newDetailIds.add(id);
                        insert.setId(id);
                        saleOrderDetailService.updateInfoById(insert);
                    } else {
                        //插入
                        saleOrderDetailService.insert(insert);
                    }
                }

                //3.不存在新列表中的则表示已经删除了
                for (MesSaleOrderDetailDTO item : historyPage.getItems()) {
                    if (!newDetailIds.contains(item.getId())) {
                        saleOrderDetailService.delete(item.getId());
                    }
                }
            }
            //endregion

            //region [02].客户原料明细表.保存成功后更新
            String[] f_id = request.getParameterValues("f_id");
            String[] f_partid = request.getParameterValues("f_partid");
            String[] f_count = request.getParameterValues("f_count");

            //1.获取已保存的原料明细
            MesOrderMaterialDTOQuery materiallHistoryQuery = new MesOrderMaterialDTOQuery();
            materiallHistoryQuery.setTableId(203);
            materiallHistoryQuery.setRecordId(objDTO.getId());
            materiallHistoryQuery.setPageSize(100);
            Page<MesOrderMaterialDTO> materialHistoryPage = orderMaterialService.getForPage(materiallHistoryQuery);

            //2. 保存到数据库
            if (f_id != null && f_id.length > 0) {

                List<Integer> newMaterailIds = new ArrayList<>(); //提交上来的，已保存过的ID
                MesOrderMaterialDTO insert;
                TransportPurchaseDTO partObj;

                for (int i = 0; i < f_id.length; i++) {
                    int count = Integer.parseInt(f_count[i]);
                    if (count <= 0) {
                        continue;
                    }

                    int partid = Integer.parseInt(f_partid[i]);
                    if (partid <= 0) {
                        continue;
                    }

                    partObj = purchaseService.getById(partid);
                    if (partObj == null) {
                        continue;
                    }

                    insert = new MesOrderMaterialDTO();
                    insert.setTableId(203);
                    insert.setRecordId(objDTO.getId());
                    insert.setPartId(partid);
                    insert.setMaterialName(partObj.getPartName());
                    insert.setMaterialNo(partObj.getPartNo());
                    insert.setCatalogId(partObj.getCatalogId());
                    insert.setGoodsType(partObj.getProductType());
                    insert.setSpecialName(partObj.getSpecialName());
                    insert.setSn(partObj.getSnCode());
                    insert.setUnit(partObj.getUnit());
                    insert.setCount(count);
                    insert.setCountSingle(0);
                    insert.setCheckCount(0);
                    insert.setIsMaterialReady(0);
                    insert.setStorage(partObj.getStorage());
                    insert.setDeleteFlag(0);

                    //更新或插入
                    int id = Integer.parseInt(f_id[i]);
                    if (id > 0) {
                        //更新
                        newMaterailIds.add(id);
                        insert.setId(id);
                        orderMaterialService.updateInfoById(insert);
                    } else {
                        //插入
                        orderMaterialService.insert(insert);
                    }
                }

                //3.不存在新列表中的则表示已经删除了
                for (MesOrderMaterialDTO item : materialHistoryPage.getItems()) {
                    if (!newMaterailIds.contains(item.getId())) {
                        orderMaterialService.delete(item.getId());
                    }
                }
            }
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            if (orderid > 0) {
                //删除已经生成的订单
                mesSaleOrderService.delete(orderid);

                //删除销售明细
                MesSaleOrderDetailDTOQuery detailQuery = new MesSaleOrderDetailDTOQuery();
                detailQuery.setW_orderId(orderid);
                detailQuery.setDeleteFlag(1);
                saleOrderDetailService.updateInfoByQuery(detailQuery);

                //删除原料明细
                MesOrderMaterialDTOQuery materailQuery = new MesOrderMaterialDTOQuery();
                materailQuery.setW_tableId(203);
                materailQuery.setRecordId(orderid);
                materailQuery.setDeleteFlag(1);
                orderMaterialService.updateInfoByQuery(materailQuery);

                //删除审批单
                applyManageService.delete(order_apply);
            }

            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = mesSaleOrderService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = mesSaleOrderService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        MesSaleOrderDTO obj = new MesSaleOrderDTO();
        obj.setId(id);

        if (id > 0) {
            obj = mesSaleOrderService.getById(id);
        }
        model = mesSaleOrderService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

    //region 获取查询列表

    /**
     * 获取查询列表（带分页）
     *
     * @param name     关键词
     * @param from     0默认
     * @param pn       页码
     * @param pageSize 分页大小
     * @return map
     */
    @RequestMapping(value = "/selectOrderPage", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> selectOrderPage(String name, Integer from, Integer pn, Integer pageSize) {
        pn = (pn == null || pn <= 0) ? 1 : pn;
        pageSize = (pageSize == null || pageSize <= 0) ? 5 : pageSize;

        Map<Object, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("pn", pn);
        map.put("pageSize", pageSize);

        MesSaleOrderDTOQuery query = new MesSaleOrderDTOQuery();
        if (StringUtils.isNotBlank(name)) {
            query.setLikeName(name.trim());
        }
        query.setNomalOrder(from);
        query.setPn(pn);
        query.setPageSize(pageSize);
        query.setStopFlag(0);
        query.setOrderBy("order by id desc");
        Page<MesSaleOrderDTO> dataPage = mesSaleOrderService.getForPage(query);

        List<MesSaleOrderDetailDTO> orderDetailList = new ArrayList<>();

        for (MesSaleOrderDTO item : dataPage.getItems()) {
            MesSaleOrderDetailDTOQuery detailQuery = new MesSaleOrderDetailDTOQuery();
            detailQuery.setOrderId(item.getId());
            detailQuery.setStopFlag(0);
            Page<MesSaleOrderDetailDTO> detailPage = saleOrderDetailService.getForPage(detailQuery);
            for (MesSaleOrderDetailDTO cItem : detailPage.getItems()) {
                cItem.setOrderName(item.getOrderTitle());
                cItem.setOrderNo(item.getOrderNo());
                cItem.setOrderStatusName(OrderStatusEnum.getEnumByKey(item.getStatus()));
                orderDetailList.add(cItem);
            }
        }

        map.put("orderDetailList", orderDetailList);
        map.put("orderAjaxPage", dataPage);
        map.put("orderAjaxPagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        return map;
    }
    //endregion

    //region 获取产品规格表中维护的原料

    /**
     * 获取产品规格表中维护的原料
     * 产品订单 -> 调销售订单 -> 再调销售订单的产品规格（mes_sale_order_detail） -> 再调规格的物料（mes_order_material）
     *
     * @param specialId 销售订单产品规格ID
     * @return map
     */
    @RequestMapping(value = "/getMaterialBySpecialId", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> getMaterialBySpecialId(Integer specialId) {
        Map<Object, Object> map = new HashMap<>();
        map.put("returnCode", 0);

        if (specialId == null || specialId <= 0) {
            return map;
        }

        MesOrderMaterialDTOQuery materiallQuery = new MesOrderMaterialDTOQuery();
        materiallQuery.setTableId(199);
        materiallQuery.setRecordId(specialId);
        materiallQuery.setPageSize(100);
        Page<MesOrderMaterialDTO> materialPage = orderMaterialService.getForPage(materiallQuery);

        //计算当前库存
        List<Map<String, String>> rmapList;
        for (MesOrderMaterialDTO item : materialPage.getItems()) {
            //库存信息
            rmapList = purchaseDetailService.selectSumCount(item.getPartId());
            if (rmapList != null) {
                Map<String, String> rmap = rmapList.get(0);
                Integer r_counts = GeneralUtils.ObjectToInt(rmap.get("r_counts"));
                Integer c_counts = GeneralUtils.ObjectToInt(rmap.get("c_counts"));
                Integer s_counts = GeneralUtils.ObjectToInt(rmap.get("s_counts"));
                item.setStockCount(r_counts - c_counts - s_counts);
            }

            item.setGoodsTypeName(ProductTypeEnum.getEnumByKey(item.getGoodsType()));
        }

        map.put("materialPage", materialPage);

        return map;
    }
    //endregion
}